package com.jingan.nursinghome.regulatory.separate;

import android.content.DialogInterface;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.jingan.nursinghome.regulatory.R;
import com.jingan.nursinghome.regulatory.adapter.MicrometerTableAdapter;
import com.jingan.nursinghome.regulatory.dialog.micrometertable.HostoryDialog;
import com.jingan.nursinghome.regulatory.dialog.micrometertable.XuantiDialog2;
import com.jingan.nursinghome.regulatory.model.Topicinfo;
import com.jingan.nursinghome.regulatory.view.MyActionBar;

import cn.android.support.v7.lib.sin.crown.base.BaseActivity;
import cn.android.support.v7.lib.sin.crown.base.BaseApplication;
import cn.android.support.v7.lib.sin.crown.base.BaseDialog;
import cn.android.support.v7.lib.sin.crown.base.BaseListenner;
import cn.android.support.v7.lib.sin.crown.dialog.AlertDialog;
import cn.android.support.v7.lib.sin.crown.utils.ProportionUtils;

/**
 * 千分表评分系统
 * Created by 彭治铭 on 2017/10/12.
 */

public class SeparateTableOSDialog extends BaseDialog {
    public static int pageIndex = 1;//当前页数。从1开始。题号。
    public static int count = 3;
    private static int maxPage;//最大页

    public static int getMaxPage() {
        maxPage = (int) Math.ceil((double) Uri.INSTANCE.getTopicinfoList().size() / (double) (count - 1));
        return maxPage;
    }

    private SeparateTableOSDialog(BaseActivity baseActivity) {
        init(baseActivity, R.layout.dialog_micrometertablleos, false);
        window.setWindowAnimations(cn.android.support.v7.lib.sin.crown.R.style.crown_window_right);
        BaseApplication.getInstance().setStatusBarDrak(window, true);
        initUI();
        //adapterUI();
    }

    public static SeparateTableOSDialog micrometerTableOSDialog;
    static String spid;

    public static SeparateTableOSDialog getInstance(BaseActivity baseActivity, String pid) {
        spid = pid;
        if (isfinish(baseActivity, micrometerTableOSDialog)) {
            micrometerTableOSDialog = new SeparateTableOSDialog(baseActivity);
        } else {
            micrometerTableOSDialog.show();
        }
        return micrometerTableOSDialog;
    }

    MyActionBar myActionBar;

    TextView txt_hostory, txt_select, txt_next, txt_next2, txt_previous;

    RecyclerView recyclerView;

    public String tihao = "";


    TextView txt_hot;

    void initHot() {
        if (txt_hot == null) {
            txt_hot = (TextView) findViewById(R.id.txt_hot);
            ProportionUtils.getInstance().adapterTextView(txt_hot);
        }
        if (Uri.INSTANCE.getTopicsHostoryQF().size() > 0) {
            txt_hot.setVisibility(View.VISIBLE);
            txt_hot.setText(Uri.INSTANCE.getTopicsHostoryQF().size() + "");
        } else {
            txt_hot.setVisibility(View.INVISIBLE);
        }
    }

    public void initUI() {

        myActionBar = (MyActionBar) findViewById(R.id.MyActionBar);
        myActionBar.setLeftBimapAndTitle(null, "千分表评分系统");
        myActionBar.setBaseListennerLeft(new BaseListenner() {
            @Override
            public void onResult(Object result) {
                onBack();
            }
        });

        txt_hostory = (TextView) findViewById(R.id.txt_hostory);
        txt_select = (TextView) findViewById(R.id.txt_select);
        txt_next = (TextView) findViewById(R.id.txt_next);
        txt_next2 = (TextView) findViewById(R.id.txt_next2);//這個隱藏。就有历史整改
        txt_next2.setVisibility(View.INVISIBLE);//这个也是下一题按钮。比较长。盖住了历史整改。
        txt_previous = (TextView) findViewById(R.id.txt_previous);
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.txt_hostory://历史整改
                        if (Uri.INSTANCE.getTopicsHostoryQF().size() > 0) {
                            HostoryDialog.getInstance(baseActivity, Uri.INSTANCE.getTopicsHostoryQF());
                        } else {
                            //ToastUtils.showToastView("暂无历史整改");
                            baseActivity.SnackbarMake("暂无历史整改", true, findViewById(R.id.dialog_micrometertableos_constraintLayout));
                        }
                        break;
                    case R.id.txt_select://选题
                        XuantiDialog2.getInstance(baseActivity, Uri.INSTANCE.getTopicinfoList(), pageIndex, new BaseListenner<Integer>() {
                            @Override
                            public void onResult(Integer result) {
                                //返回当前页面
                                pageIndex = result;
                                //recyclerView.smoothScrollToPosition(pageIndex);
                                //linearLayoutManager.scrollToPosition(pageIndex);
                                linearLayoutManager.scrollToPositionWithOffset(pageIndex - 1, 0);
                            }
                        });
                        break;
                    case R.id.txt_previous://上一题
                        pageIndex -= 2;//退2倒题。
                        if (pageIndex <= 0) {
                            pageIndex = 0;
                        }
                        canScrollVertically = true;
                        linearLayoutManager.scrollToPositionWithOffset(pageIndex, 0);
                        break;
                    case R.id.txt_next://下一题
                    case R.id.txt_next2:
                        //txt_next.requestFocusFromTouch();
                        recyclerView.clearFocus();//失去焦点，记录备注文本
                        if (pageIndex > linearLayoutManager.findLastCompletelyVisibleItemPosition()) {
                            pageIndex = linearLayoutManager.findLastCompletelyVisibleItemPosition();
                        }
                        Log.e("ui", "pageIndex:\t" + pageIndex + "\t" + Uri.INSTANCE.getTopicinfoList().size() + "\t" + linearLayoutManager.findLastCompletelyVisibleItemPosition());
                        if (pageIndex >= Uri.INSTANCE.getTopicinfoList().size() || linearLayoutManager.findLastCompletelyVisibleItemPosition() == (Uri.INSTANCE.getTopicinfoList().size() - 1)) {
                            //最后一页
                            int score = 0;//得分。
                            int maxScore = 0;//总分
                            tihao = "";

                            pageIndex = Uri.INSTANCE.getTopicinfoList().size();

//                            Log.e("ui","总数:\t"+ Uri.INSTANCE.getTopicinfoList().size());
//                            Log.e("ui","类型:\t"+ Uri.INSTANCE.getTopicinfoList().get(0).getTopic_type());
                            //当前题目的得分和总分
                            for (int i = 0; i < Uri.INSTANCE.getTopicinfoList().size(); i++) {
                                String sp_type = Uri.INSTANCE.getTopicinfoList().get(i).getTopic_type();
//                                Log.e("test","类型:\t"+sp_type);
                                if ((sp_type != null && sp_type.trim().equals("2")) || Uri.INSTANCE.getTopicinfoList().get(i) == null || Uri.INSTANCE.getTopicinfoList().get(i).getTopic_score() == null) {
                                    continue;//违法题
                                }
//                                Log.e("ui","总分:\t"+Uri.INSTANCE.getTopicinfoList().get(i).getTopic_score()+"\t下标:\t"+i);
                                maxScore = maxScore + Uri.INSTANCE.getTopicinfoList().get(i).getTopic_score();
                                String c = Uri.INSTANCE.getTopicinfoList().get(i).getPscore();
                                if (c != null && !c.trim().equals("")) {
                                    score = score + Integer.valueOf(c);
                                }
                            }
                            //历史整改的得分和总分
                            if (Uri.INSTANCE.getTopicsHostoryQF().size() > 0) {
                                for (int i = 0; i < Uri.INSTANCE.getTopicsHostoryQF().size(); i++) {
                                    if (Uri.INSTANCE.getTopicsHostoryQF().get(i) == null || Uri.INSTANCE.getTopicsHostoryQF().get(i).getTopic_score() == null) {
                                        continue;
                                    }
                                    maxScore = maxScore + Integer.valueOf(Uri.INSTANCE.getTopicsHostoryQF().get(i).getTopic_score());
                                    String c = Uri.INSTANCE.getTopicsHostoryQF().get(i).getPscore();
                                    if (c != null && !c.trim().equals("")) {
                                        score = score + Integer.valueOf(c);
                                    }
                                }
                            }

                            for (int i = 0; i < Uri.INSTANCE.getTopicinfoList().size(); i++) {
                                Topicinfo topicinfo = Uri.INSTANCE.getTopicinfoList().get(i);
                                if (topicinfo == null || topicinfo.getTopic_score() == null || (topicinfo.getTopic_type() != null && topicinfo.getTopic_type().trim().equals("2"))) {
                                    continue;
                                }
                                String num = (i + 1) + "";//题号
                                String c = Uri.INSTANCE.getTopicinfoList().get(i).getPscore();
                                if (c == null || c.equals("")) {
                                    if (tihao.equals("")) {
                                        tihao = num;
                                    } else {
                                        tihao = tihao + "," + num;
                                    }
                                }
                            }
                            //fixme ======================================================跳转到提交页
                            Log.e("ui", "下一页：\tmaxScore:\t" + maxScore + "\tscore:\t" + score);
                            SeparateCommitDailog.getInstance(baseActivity, micrometerTableOSDialog, maxScore + "", score + "", spid);
                            break;
                        }
                        if (linearLayoutManager.findLastCompletelyVisibleItemPosition() > 0) {
                            pageIndex = linearLayoutManager.findLastCompletelyVisibleItemPosition() + 1;
                        } else {
                            if (linearLayoutManager.findFirstVisibleItemPosition() == linearLayoutManager.findLastVisibleItemPosition()) {
                                pageIndex = linearLayoutManager.findLastVisibleItemPosition() + 1;
                            } else {
                                pageIndex = linearLayoutManager.findLastVisibleItemPosition();
                            }
                        }
                        if (pageIndex >= Uri.INSTANCE.getTopicinfoList().size()) {
                            pageIndex = Uri.INSTANCE.getTopicinfoList().size();
                        }
                        canScrollVertically = true;
                        linearLayoutManager.scrollToPositionWithOffset(pageIndex, 0);
                        break;
                }
            }
        };
        txt_hostory.setOnClickListener(onClickListener);
        txt_select.setOnClickListener(onClickListener);
        txt_next.setOnClickListener(onClickListener);
        txt_next2.setOnClickListener(onClickListener);
        txt_previous.setOnClickListener(onClickListener);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        linearLayoutManager = new LinearLayoutManager(baseActivity) {
            @Override
            public boolean canScrollVertically() {
                return canScrollVertically;
                //return false;//禁止滑动
            }
        };
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {

                    //int postion = linearLayoutManager.findFirstVisibleItemPosition();
                    int postion = linearLayoutManager.findFirstCompletelyVisibleItemPosition();
                    pageIndex = postion + 1;
                    linearLayoutManager.scrollToPositionWithOffset(pageIndex - 1, 0);
                    canScrollVertically = false;
                }
            }
        });
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    canScrollVertically = false;
                }
                return false;
            }
        });

    }

    boolean canScrollVertically = false;
    LinearLayoutManager linearLayoutManager;

    AlertDialog alertDialog;

    void onBack() {
        alertDialog = AlertDialog.getInstance(baseActivity, false, true).setMession("是否退出本次评分?");
        alertDialog.setPositive("是", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                alertDialog.dismiss();
            }
        });
    }

    public void adapterUI() {
        ProportionUtils.getInstance().adapterScreen(baseActivity, findViewById(R.id.dialog_micrometertableos_constraintLayout));
        ProportionUtils.getInstance().adapterTextView(txt_hostory);
        ProportionUtils.getInstance().adapterTextView(txt_select);
        ProportionUtils.getInstance().adapterTextView(txt_next);
        ProportionUtils.getInstance().adapterTextView(txt_next2);
        ProportionUtils.getInstance().adapterTextView(txt_previous);
    }

    @Override
    protected void listener() {
        pageIndex = 1;
        recyclerView.setAdapter(new MicrometerTableAdapter(baseActivity, Uri.INSTANCE.getTopicinfoList()));
        initHot();

        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getAction() == KeyEvent.ACTION_DOWN) {
                    onBack();
                    return true;//记得返回true。表示已经处理。
                }
                return false;//返回键以外交给系统自行处理。不可以屏蔽，不然输入法键盘的按键可能无效。如删除键
            }
        });

    }

    //更新
    public void updateAdapter() {
        recyclerView.setAdapter(new MicrometerTableAdapter(baseActivity, Uri.INSTANCE.getTopicinfoList()));
    }

    @Override
    protected void recycleView() {
        Uri.INSTANCE.putCache(spid);//缓存题目
    }

    @Override
    protected boolean isRecycel() {
        return false;
    }
}
